package com.sgb.merchant.view.activity;

import android.content.Context;
import android.content.Intent;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.TypedValue;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.util.Pair;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.fondesa.recyclerviewdivider.DividerDecoration;
import com.google.android.material.tabs.TabLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;
import com.sgb.link.entity.merchant.IndustryCategoryEntity;
import com.sgb.link.entity.merchant.InvestmentProjectEntity;
import com.sgb.link.entity.merchant.TradeCategoryEntity;
import com.sgb.link.router.PathMerchant;
import com.sgb.link.view.widget.CustomXTabLayout;
import com.sgb.merchant.R;
import com.sgb.merchant.databinding.MerchantActivityInvestmentProjectBinding;
import com.sgb.merchant.view.adapter.InvestmentProjectAdapter;
import com.sgb.merchant.viewmodel.InvestmentProjectViewmodel;
import com.sgb.merchant.widget.ProjectFilterPopWindow;
import com.swgk.core.base.model.entity.RouterKey;
import com.swgk.core.common.base.BaseActivity;
import com.swgk.core.common.utils.ActivityJump;
import com.swgk.core.dialog.BasePopWindow;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.recyclerview.adapter.AdapterOnItemClick;
import com.swgk.core.util.MToast;
import com.swgk.core.view.areapopup.AddressEntity;
import com.swgk.core.view.areapopup.ThreeLevelAreaWindow;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static android.view.View.GONE;
import static android.view.View.VISIBLE;

/**
 * Time:2021/6/18
 * Author:黄淋
 * Description: 投资项目列表页
 */
@Route(path = PathMerchant.InvestmentProjectActivity)
public class InvestmentProjectActivity extends BaseActivity {
    MerchantActivityInvestmentProjectBinding mBinding;
    private InvestmentProjectAdapter mAdapter;
    InvestmentProjectViewmodel mViewModel;
    Map<String, Object> mMap;
    private boolean mIsLoadMore = false;
    private ThreeLevelAreaWindow mAddressPop;
    private boolean isChange2;
    private List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> cityDatas;

    private static int STATE_PUBLISH_TIME = 0;
    private final static int STATE_PUBLISH_TIME_UP = 1;
    private final static int STATE_PUBLISH_TIME_DOWN = 2;
    private final static int STATE_PUBLISH_TIME_NONE = 0;
    private int STATE_END_TIME = 0;
    private final static int STATE_END_TIME_UP = 1;
    private final static int STATE_END_TIME_DOWN = 2;
    private final static int STATE_END_TIME_NONE = 0;
    private boolean mIsHasSearch = false;
    Long no;
    ProjectFilterPopWindow mFilterPop;
    private String cityName;

    public static void start(Context context) {
        Intent intent = new Intent();
        intent.setClass(context, InvestmentProjectActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected int layoutId() {
        return R.layout.merchant_activity_investment_project;
    }

    @Override
    protected void createViewModel() {

    }

    @Override
    protected void init() {
        mBinding = DataBindingUtil.setContentView(this, R.layout.merchant_activity_investment_project);
        mViewModel = new ViewModelProvider(this).get(InvestmentProjectViewmodel.class);
        initActionBar();
        initAdapter();
        initWindow();
        mFilterPop=new ProjectFilterPopWindow(this);
        mFilterPop.setBgView(mBinding.popTransparentLayout);
        mFilterPop.setOnResultCallBack(new BasePopWindow.OnResultCallBack() {
            @Override
            public void result(Object result) {
                Map<String, Object> map= (Map<String, Object>) result;
                if(map.isEmpty()){
                    mMap.remove("taxDiscountNo");
                    mMap.remove("stageNo");
                    mMap.remove("landDiscountNo");
                }else{
                    mMap.putAll(map);

                }
                mIsLoadMore = false;
                getData();
            }
        });

        mBinding.rlPublishTime.setOnClickListener(view -> {


            setMoneyState(STATE_END_TIME_NONE);
            mMap.remove("itemMoney");
            if (STATE_PUBLISH_TIME == STATE_PUBLISH_TIME_NONE) {
                setPublishState(STATE_PUBLISH_TIME_UP);
                mMap.put("createTime", "asc");
            } else if (STATE_PUBLISH_TIME == STATE_PUBLISH_TIME_UP) {
                setPublishState(STATE_PUBLISH_TIME_DOWN);
                mMap.put("createTime", "desc");
            } else {
                setPublishState(STATE_PUBLISH_TIME_UP);
                mMap.put("createTime", "asc");
            }
            mIsLoadMore = false;
            getData();
        });
        mBinding.rlMoney.setOnClickListener(view -> {

            setPublishState(STATE_END_TIME_NONE);
            mMap.remove("createTime");
            if (STATE_END_TIME == STATE_END_TIME_NONE) {
                setMoneyState(STATE_END_TIME_UP);
                mMap.put("itemMoney", "asc");
            } else if (STATE_END_TIME == STATE_END_TIME_UP) {
                setMoneyState(STATE_END_TIME_DOWN);
                mMap.put("itemMoney", "desc");
            } else {
                setMoneyState(STATE_END_TIME_UP);
                mMap.put("itemMoney", "asc");
            }
            mIsLoadMore = false;
            getData();
        });

        mMap = new HashMap<>();
        mMap.put("createTime", "desc");
//        mMap.put("proviceId", SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.AreaCode, ""));
        getData();
        mViewModel.liveDataInvestment.observe(this, list -> showProjectList(list, mIsLoadMore));

        mViewModel.getindustryFirstCategoryList();
        mViewModel.liveDataCategoryList.observe(this, this::showTabLayout);

        mViewModel.liveDataCityList.observe(this, this::showCityPopWindow);
        mViewModel.ldState.observe(this,state->{
            switch (state){//0未上架 1已删除 2正常
                case 0:
                    MToast.showToast(this,"当前数据已下架");
                    DialogHelper.showProgressDialog(this, null, "数据加载中...", 0, false, null).setCanceledOnTouchOutside(false);
                    mIsLoadMore = false;
                    getData();
                    break;
                case 1:
                    MToast.showToast(this,"当前数据已删除");
                    DialogHelper.showProgressDialog(this, null, "数据加载中...", 0, false, null).setCanceledOnTouchOutside(false);
                    mIsLoadMore = false;
                    getData();
                    break;
                case 2:
                    ActivityJump.startActivity(PathMerchant.InvestmentDetailActivity, Pair.create(RouterKey.NO,no));
                    break;
            }
        });
        mViewModel.ldOptions.observe(this,data->{
            IndustryCategoryEntity entity=new IndustryCategoryEntity();
            entity.setCategoryNo("");
            entity.setCategoryName("不限");
            if(data.getTaxDiscountOptions()!=null) {
                data.getTaxDiscountOptions().add(0,entity);
                mFilterPop.setRevenueType(data.getTaxDiscountOptions());
            }else{
                List<IndustryCategoryEntity> taxDiscount=new ArrayList<>();
                taxDiscount.add(0,entity);
                mFilterPop.setRevenueType(taxDiscount);
            }
            if(data.getLandDiscountOptions()!=null){
                data.getLandDiscountOptions().add(0,entity);
                mFilterPop.setLandType(data.getLandDiscountOptions());
            }else{
                List<IndustryCategoryEntity> landDiscount=new ArrayList<>();
                landDiscount.add(0,entity);
                mFilterPop.setLandType(landDiscount);
            }
            if(data.getStageOptions()!=null){
                data.getStageOptions().add(0,entity);
                mFilterPop.setStageType(data.getStageOptions());
            }else{
                List<IndustryCategoryEntity> stage=new ArrayList<>();
                stage.add(0,entity);
                mFilterPop.setStageType(stage);
            }
            mFilterPop.showPopwindowRight(mBinding.llMore);
        });
    }

    private void initActionBar() {
        mBinding.includeActionBar.ivBackRed.setOnClickListener(a -> finish());
        mBinding.includeActionBar.editSearchRed.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (mBinding.includeActionBar.editSearchRed.getText().toString().equals("")) {
                    mBinding.includeActionBar.ivCloseRed.setVisibility(GONE);
                } else {
                    mBinding.includeActionBar.ivCloseRed.setVisibility(VISIBLE);
                }
            }
        });
        mBinding.includeActionBar.editSearchRed.setImeOptions(EditorInfo.IME_ACTION_SEARCH);
        mBinding.includeActionBar.editSearchRed.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                closeKeybord();
                if (actionId == EditorInfo.IME_ACTION_SEARCH || (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
                    mIsHasSearch = true;
                    if (TextUtils.isEmpty(mBinding.includeActionBar.editSearchRed.getText().toString())) {
                        MToast.showToast(InvestmentProjectActivity.this, "请输入项目名称");
                        return true;
                    }
                    DialogHelper.showProgressDialog(InvestmentProjectActivity.this, "搜索中").setCanceledOnTouchOutside(true);
                    mIsHasSearch = true;
                    closeKeybord();
                    mMap.put("itemName", mBinding.includeActionBar.editSearchRed.getText().toString());
                    mIsLoadMore = false;
                    getData();
                }
                return false;
            }
        });
        mBinding.includeActionBar.ivCloseRed.setOnClickListener(v -> {
            mBinding.includeActionBar.editSearchRed.setText("");
            if (mIsHasSearch) {
                closeKeybord();
                mMap.remove("itemName");
                mIsLoadMore = false;
                getData();
            }
        });

        mBinding.includeActionBar.rightViewRed.setOnClickListener(a -> {
            if (mBinding.includeActionBar.editSearchRed.getText().toString().equals("")) {
                MToast.showToast(InvestmentProjectActivity.this, "请输入项目名称");
            }
            //搜索
            mIsHasSearch = true;
            closeKeybord();
            mMap.put("itemName", mBinding.includeActionBar.editSearchRed.getText().toString());
            mIsLoadMore = false;
            getData();
        });

        mBinding.llMore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(mViewModel.ldOptions.getValue()!=null) {
                    mFilterPop.showPopwindowRight(mBinding.llMore);
                }else{
                    mViewModel.getOptions();
                }
            }
        });
        mBinding.tvLocation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!TextUtils.isEmpty(cityName)){
                    mBinding.tvLocation.updateChooseTextStatus(-2, cityName);
                }else {
                    mBinding.tvLocation.updateChooseTextStatus(-2, mBinding.tvLocation.getKeyName());
                }
                if (cityDatas == null) {
                    DialogHelper.showProgressDialog(InvestmentProjectActivity.this, null, "", 0, false, null).setCanceledOnTouchOutside(true);
                    mViewModel.getServiceCity();
                } else {
                    mAddressPop.setData(cityDatas, true);
                    mAddressPop.showPopwindow0(mBinding.llChoose);
                }
            }
        });
    }

    private void initWindow() {
        mAddressPop = new ThreeLevelAreaWindow(this){
            @Override
            protected void resultContent(String name, String simpleName) {
                if (name.equals("全国")) {
                    cityName="不限";
                    mBinding.tvLocation.updateChooseTextStatus(1,"不限");
                } else {
                    cityName=simpleName;
                    mBinding.tvLocation.updateChooseTextStatus(1,simpleName);

                }
            }
        };
        mAddressPop.setMemberHeight();
        mAddressPop.setAllSingleSelect(true);
        mAddressPop.setProvinceSingle();
        mAddressPop.setCitySingle();
        mAddressPop.setAreaSingle();
        mAddressPop.setBgView(mBinding.grayLayoutInvestment);
        mAddressPop.setOnResultClick(new ThreeLevelAreaWindow.OnResultClickProxy() {
            @Override
            protected void result(com.swgk.core.view.areapopup.GoodsSourceLocationEntity entity) {
                isChange2=true;
                if (entity.getProvinceNo() == null || entity.getProvinceNo().equals("")) {
                    mMap.remove("proviceId");
                    mMap.remove("cityId");
                    mMap.remove("regionId");
                    mIsLoadMore = false;
                    getData();
                    return;
                }
                mMap.put("proviceId", entity.getProvinceNo());
                mMap.put("cityId", entity.getCityNo());
                mMap.put("regionId", entity.getAreaNo());
                mIsLoadMore = false;
                getData();
            }
        });
        mAddressPop.setOnDismissListener(() -> {
            if (isChange2) {
                mBinding.tvLocation.updateChooseTextStatus(1, null);
            } else {
                mBinding.tvLocation.updateChooseTextStatus(0, mBinding.tvLocation.getKeyName());
            }
        });


    }


    private void initAdapter() {
        mBinding.displayView.setLayoutManager(new LinearLayoutManager(this));
        DividerDecoration.builder(this)
                .color(getResources().getColor(R.color.color_f5f5f5))
                .size(1, TypedValue.COMPLEX_UNIT_DIP)
                .build()
                .addTo(mBinding.displayView);
        mAdapter = new InvestmentProjectAdapter(this, null);
        mAdapter.setOnItemClick(new AdapterOnItemClick<InvestmentProjectEntity>() {
            @Override
            public void onItemClick(InvestmentProjectEntity investmentProjectEntity, int position) {
                no=investmentProjectEntity.getNo();
                mViewModel.getState(investmentProjectEntity.getNo());

            }
        });
        mBinding.displayView.setAdapter(mAdapter);
        mBinding.refreshLayout.setEnableRefresh(true);
        mBinding.refreshLayout.setEnableLoadMore(true);
        mBinding.refreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                mIsLoadMore = true;
                getData();
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                mIsLoadMore = false;
                getData();
            }
        });
    }

    private void getData() {
        mViewModel.getInvestmentData(mIsLoadMore, mMap);
    }

    @Override
    public void onClick(View v) {


    }

    private void setPublishState(int state) {
        switch (state) {
            case STATE_PUBLISH_TIME_DOWN://降序
                STATE_PUBLISH_TIME = STATE_PUBLISH_TIME_DOWN;
                mBinding.rlPublishTime.setBackground(getResources().getDrawable(R.drawable.search_new_blue_bg));
                mBinding.imgPublishUp.setImageResource(R.mipmap.icn_up_arrow_n);
                mBinding.imgPublishDown.setImageResource(R.mipmap.icon_down_red);
                mBinding.tvPublishContent.setTextColor(getResources().getColor(R.color.color_EF4033_link));
                break;
            case STATE_PUBLISH_TIME_UP://升序
                STATE_PUBLISH_TIME = STATE_PUBLISH_TIME_UP;
                mBinding.rlPublishTime.setBackground(getResources().getDrawable(R.drawable.search_new_blue_bg));
                mBinding.imgPublishUp.setImageResource(R.mipmap.icon_up_red);
                mBinding.imgPublishDown.setImageResource(R.mipmap.ic_down_arrow_n);
                mBinding.tvPublishContent.setTextColor(getResources().getColor(R.color.color_EF4033_link));
                break;
            case STATE_PUBLISH_TIME_NONE://未选择
                STATE_PUBLISH_TIME = STATE_PUBLISH_TIME_NONE;
                mBinding.rlPublishTime.setBackground(getResources().getDrawable(R.drawable.search_bg));
                mBinding.imgPublishUp.setImageResource(R.mipmap.icn_up_arrow_n);
                mBinding.imgPublishDown.setImageResource(R.mipmap.ic_down_arrow_n);
                mBinding.tvPublishContent.setTextColor(getResources().getColor(R.color.FF333333));
                break;
        }
    }

    private void setMoneyState(int state) {
        switch (state) {
            case STATE_END_TIME_DOWN://降序
                STATE_END_TIME = STATE_END_TIME_DOWN;
                mBinding.rlMoney.setBackground(getResources().getDrawable(R.drawable.search_new_blue_bg));
                mBinding.imgEndUp.setImageResource(R.mipmap.icn_up_arrow_n);
                mBinding.imgEndDown.setImageResource(R.mipmap.icon_down_red);
                mBinding.tvEndContent.setTextColor(getResources().getColor(R.color.color_EF4033_link));
                break;
            case STATE_END_TIME_UP://升序
                STATE_END_TIME = STATE_END_TIME_UP;
                mBinding.rlMoney.setBackground(getResources().getDrawable(R.drawable.search_new_blue_bg));
                mBinding.imgEndUp.setImageResource(R.mipmap.icon_up_red);
                mBinding.imgEndDown.setImageResource(R.mipmap.ic_down_arrow_n);
                mBinding.tvEndContent.setTextColor(getResources().getColor(R.color.color_EF4033_link));
                break;
            case STATE_END_TIME_NONE://未选择
                STATE_END_TIME = STATE_END_TIME_NONE;
                mBinding.rlMoney.setBackground(getResources().getDrawable(R.drawable.search_bg));
                mBinding.imgEndUp.setImageResource(R.mipmap.icn_up_arrow_n);
                mBinding.imgEndDown.setImageResource(R.mipmap.ic_down_arrow_n);
                mBinding.tvEndContent.setTextColor(getResources().getColor(R.color.FF333333));
                break;
        }
    }

    /**
     * 数据
     *
     * @param list
     * @param isLoadMore
     */
    public void showProjectList(List<InvestmentProjectEntity> list, boolean isLoadMore) {
        DialogHelper.dismissProgressDialog();
        mBinding.refreshLayout.finishRefresh();
        mBinding.refreshLayout.finishLoadMore();
        if (isLoadMore) {
            mBinding.errorView.setVisibility(View.GONE);
            if (null != list && list.size() > 0) {
                mBinding.refreshLayout.resetNoMoreData();
                mAdapter.addDatas(list);
            } else {
                mBinding.refreshLayout.finishLoadMoreWithNoMoreData();
            }
            mBinding.displayView.setVisibility(View.VISIBLE);
        } else {
            if (null != list && list.size() > 0) {
                mBinding.displayView.setVisibility(View.VISIBLE);
                mBinding.errorView.setVisibility(View.GONE);
                mAdapter.setDatas(list);
            } else {
                mAdapter.setDatas(null);
                mBinding.displayView.setVisibility(View.GONE);
                mBinding.errorView.setVisibility(View.VISIBLE);
            }
        }
    }

    private void showTabLayout(List<TradeCategoryEntity> list) {
        TradeCategoryEntity entity = new TradeCategoryEntity();
        entity.setCategroyName("全部");
        entity.setNo(null);
        list.add(0, entity);

        for (int a = 0; a < list.size(); a++) {
            mBinding.tabIndustryCategory.addTab(mBinding.tabIndustryCategory.newTab().setText(list.get(a).getCategroyName()).setTag(list.get(a).getNo()));
        }
        mBinding.tabIndustryCategory.addOnTabSelectedListener(new CustomXTabLayout.SimpleSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                mMap.put("categoryFirst", tab.getTag());
                resetChoose();
                mIsLoadMore = false;
                isChange2 = false;
                getData();
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }

    public void showCityPopWindow(List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> cityDatas) {
        this.cityDatas = cityDatas;
        String proName = "不限", cityName = "不限", areaName = "不限";
        mAddressPop.setDataAndPosition(cityDatas, proName, cityName, areaName, true, true);
        mAddressPop.showPopwindow0(mBinding.llChoose);
    }

    /**
     * 重置筛选
     */
    private void resetChoose() {
        cityName="";
        mBinding.tvLocation.updateChooseTextStatus(0, "地区");
        initWindow();
        mFilterPop.setRest();
        setPublishState(STATE_END_TIME_NONE);
        setMoneyState(STATE_END_TIME_NONE);
        mMap.remove("taxDiscountNo");
        mMap.remove("stageNo");
        mMap.remove("landDiscountNo");
        mMap.remove("proviceId");
        mMap.remove("cityId");
        mMap.remove("regionId");
        mMap.remove("itemMoney");
        mMap.put("createTime", "desc");
    }

}
